package com.PlantVsZombies.game;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.PlantVsZombies.constant.GameVariable;
import com.PlantVsZombies.db.dao.PlayerDao;
import com.PlantVsZombies.db.model.Player;
import com.PlantVsZombies.util.StringUtil;

public class PlayerPanel extends JPanel{


	private JTextField jTextField0;
	private JButton jButton0;
	private JButton jButton1;
	private JFrame frame;
	private PlayerDao playerDao = new PlayerDao();

	private void initComponents() {
		setLayout(null);
		add(getJTextField0());
		add(getJButton0());
		add(getJButton1());
		setSize(530, 101);
	}

	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("确认");
			jButton1.setBounds(387, 36, 81, 28);
			jButton1.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					String player = jTextField0.getText().trim();
					if (StringUtil.isEmpty(player)) {
						JOptionPane.showConfirmDialog(null, "玩家名不能为空", "温馨提示!", JOptionPane.DEFAULT_OPTION);
						return;
					}
					Player p = playerDao.select(player);
					if (p != null) {
						GameVariable.player = player;
						frame.dispose();
					} else {
						p = new Player();
						p.setName(player);
						p.setTime(new Date());
						if (playerDao.insertPlayer(p)){
							GameVariable.player = player;
							frame.dispose();
						} else {
							return;
						}
					}
					MainFrame.P.remove(MainFrame.welcome);
					MainFrame.P.add(MainFrame.m);
					//MainFrame.m.setVisible(true);
					Welcome.welcome.stop();
					Menu.menu.loop();
					MainFrame.P.setVisible(true);
					MainFrame.P.setFocusable(true);
					MainFrame.P.repaint();
				}
			});
		}
		return jButton1;
	}

	private JButton getJButton0() {
		if (jButton0 == null) {
			jButton0 = new JButton();
			jButton0.setText("随机生成");
			jButton0.setBounds(281, 36, 86, 28);
		}
		return jButton0;
	}

	private JTextField getJTextField0() {
		if (jTextField0 == null) {
			jTextField0 = new JTextField("请输入玩家姓名");
			jTextField0.setBounds(59, 32, 205, 35);
			jTextField0.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					jTextField0.setText("");
				}
			});
			
		}
		return jTextField0;
	}

	public PlayerPanel(JFrame frame) {
		this.frame = frame;
		initComponents();
	}

}
